<template>
  <div class="page-container">


    <div style="overflow:hidden; padding-bottom:15px;">

      <!--左边面板（开始）-->
      <div class="page-td">
        <div class="page-box">
          <h3 class="title">角色管理</h3>
          <div class="box">

            <!--操作栏【开始】-->
            <el-row class="page-optbutton">
              <el-button size="mini" type="primary" @click="addRole()">创建角色</el-button>

            </el-row>
            <!--操作栏【结束】-->

            <!--角色列表【开始】-->
            <!--列表【开始】-->
            <div class="page-listtable">
              <el-table
                ref="dataTableRef"
                v-loading="listLoading"
                :data="roleList"
                element-loading-text="列表加载中..."
                border
                fit
                highlight-current-row
                @selection-change="tableSelectionChange"
                @row-click="clickRow"
                size="small"
                max-height="550"
              >

                <el-table-column label="序号" align="center" width="50">
                  <template slot-scope="scope">{{scope.$index+1}}</template>
                </el-table-column>
                <!--序号（结束）-->

                <!--表的其中已列（开始）-->
                <el-table-column label="名称" align="center" >
                  <template slot-scope="scope" >
                    <div :title="scope.row.desrc">{{ scope.row.name }}</div>
                  </template>
                </el-table-column>

                <el-table-column label="所有权限" align="center" width="100" >
                  <template slot-scope="scope">
                    <div v-if="scope.row.hasAllRight==1" style="color: #18bc9c;">开启</div>
                    <div v-if="scope.row.hasAllRight==2">关闭</div>
                  </template>
                </el-table-column>

                <el-table-column label="排序" align="center" width="80" >
                  <template slot-scope="scope">{{ scope.row.sortOrder }}</template>
                </el-table-column>
                <!--表的其中已列（结束）-->
                <el-table-column label="状态" align="center" width="80" >
                  <template slot-scope="scope">
                    <div v-if="scope.row.status==1" style="color: #18bc9c;">正常</div>
                    <div v-if="scope.row.status!=1" style="color: red;">禁用</div>
                  </template>
                </el-table-column>
                <!--操作栏（开始）-->
                <el-table-column align="center" label="操作" width="180">
                  <template slot-scope="scope">
                    <el-button size="mini"  type="primary" plain :data-id="scope.row.id" @click="editRole(scope.row)" >编辑</el-button>
                    <el-button size="mini"  type="danger" plain :data-id="scope.row.id" @click="delRole(scope.row)" >删除</el-button>
                  </template>
                </el-table-column>
                <!--操作栏（结束）-->



              </el-table>
            </div>
            <!--角色列表【结束】-->

          </div>
        </div>
      </div>
      <!--左边面板（结束）-->


      <!--右边面板（开始）-->
      <div class="page-td" v-loading="loading"
           element-loading-text="保存中"
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-tabs type="border-card"   v-model="viewTabactiveName">
          <el-tab-pane label="菜单" name="menuTab"></el-tab-pane>
        </el-tabs>
        <div class="page-box" style="margin-bottom:10px;" >
          <div class="box">

            <!--操作栏【开始】-->
            <el-row class="page-optbutton">
              <el-button size="mini" type="success"  @click="saveRoleMenu()">保存权限</el-button>
              <span style="padding:0 20px 0 20px;" v-if="roleName!=''">当前选中的角色： {{roleName}}</span>
              <el-checkbox v-model="cascadeChecked" >是否联级选择</el-checkbox>
            </el-row>
            <!--操作栏【结束】-->

            <!--树形列表【开始】-->
            <el-tree
              :data="menuList"
              show-checkbox
              :check-strictly="!cascadeChecked"
              node-key="id"
              :default-expand-all="false"
              ref="menuTree"
              @check-change="handleCheckChange"
              max-height="550"
              :props="menuTreeProps">
            </el-tree>
            <!--树形列表【结束】-->
          </div>
        </div>


      </div>
      <!--右边面板（结束）-->
    </div>



    <el-dialog  :title="dialogTitle"  v-if="sysRoleDialogVisible"
                :visible.sync="sysRoleDialogVisible"
                :closeOnClickModal="false"  width="1300px" >
      <sysRoleDialog :dataObj="selObj"  v-if="sysRoleDialogVisible" ref="sysRoleDialogRef" @closeDialog="closeDialog"></sysRoleDialog>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="$refs.sysRoleDialogRef.save()" >保存</el-button>
        <el-button @click="sysRoleDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  //cjianquan 2019/11/12
  import {sysRoleAllList,addSysRole,modifySysRole,deleteSysRole} from "@/api/system/sysRole.js";
  import {sysMenuTreeList} from "@/api/system/sysMenu.js";
  import {sysRoleMenuAllList,saveSysRoleMenu} from "@/api/system/sysRoleMenu.js";

  import sysRoleDialog from '@/views/system/dialog/sysRoleDialog.vue';


  export default {
    name: 'role',
    components: {
      sysRoleDialog,
    },
    filters: {
    },
    data() {
      return {
        menuTreeProps: {
          children: 'children',
          label: 'label',
          parentId:'parentId',
          type:'type',
        },
        roleList: [],
        menuList:[],
        listLoading: true,
        viewTabactiveName:"crm",
        roleId:'',
        roleName:'',

        permissionIds:'',//即menuIds
        saveDisabled:true,
        saveHint:'请选择角色',
        hasAllRight:false,
        formLabelWidth:'130px',//表单宽度
        form:{},
        editMode:0,

        cascadeChecked:false,
        loading:false,

        //cjianquan 2019/11/12
        selArr:[],
        selObj:new Object(),
        dialogTitle:'编辑',
        sysRoleDialogVisible:false,
        idArr:[],
      }
    },
    created() {
      this.getTableList();
      this.getMenuList();
    },
    computed: {
      ...mapGetters([
        'name',
        'roles',
        'avatar'
      ])
  },
  methods: {

    /**获取角色列表**/
    getTableList() {
      this.listLoading = true
      sysRoleAllList().then(response => {
        this.roleList=response.data;
        this.listLoading = false
      })
    },
    /**权限列表**/
    getMenuList() {
      var sqlWhere = " and hidden is null or hidden!=1 ";
      sysMenuTreeList({sqlWhere:sqlWhere}).then(response => {
        this.menuList=response.data;
      })
    },

    /**根据角色获取权限**/
    getRoleMenu() {
      sysRoleMenuAllList({roleId:this.roleId}).then(response => {
        var roleMenuList = response.data;
        console.log("roleMenuList...",roleMenuList)
        var menuIdList =[];
        for (var i=0;i<roleMenuList.length;i++){
          menuIdList.push(roleMenuList[i].menuId);
        }
        this.$refs.menuTree.setCheckedKeys(menuIdList);
      })
    },

    //cjianquan 2019/8/27 提交同步，分次提交
    async saveRoleMenu() {
      this.loading = true;
      var savePermobj = new Object();
      savePermobj.roleId=this.roleId;
      var permIdArr = [];
      if(this.permissionIds){
        permIdArr = this.permissionIds.split(",");
      }
      var index = 0;
      var tmpPermIdArr = [];
      var successFlag = false;
      if(permIdArr.length==0){
        permIdArr.push(-1)
      }
      while(true){
        if(permIdArr.length==0){
          break;
        }

        var permId = permIdArr[0];
        permIdArr.shift();
        if(!permId){
          break;
        }
        tmpPermIdArr.push(permId);
        index++
        if(index>100){
          index = 0 ;
          savePermobj.menuIds = tmpPermIdArr.join(",");
          tmpPermIdArr = [];
          await saveSysRoleMenu(savePermobj).then(response => {
            successFlag = response.data.success;
            savePermobj.id = response.data.record;
          });
          if(!successFlag){
            break;
          }
        }
      }
      if(tmpPermIdArr && tmpPermIdArr.length>0){
        savePermobj.menuIds = tmpPermIdArr.join(",");
        tmpPermIdArr = [];
        await saveSysRoleMenu(savePermobj).then(response => {
          successFlag = response.data.success;
          savePermobj.id = response.data.record;
        });
      }
      if(successFlag){//成功
        this.$notify({
          title: '保存成功',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      }else{//失败
        this.$notify({
          title: '保存失败',
          message: '保存失败',
          type: 'danger',
          duration: 2000
        })
      }
      this.loading = false;
    },


    //cjianquan 2019/7/22
    handleCheckChange(_node,_chk,_childChk){
      if(!this.cascadeChecked){
        this.checkParentNodes(_node.parentId,_chk);
      }
      var c_list = this.$refs.menuTree.getCheckedNodes(false,true);
      var ids ='';
      for (var i=0;i<c_list.length;i++){
        ids+=c_list[i].id+",";
      }
      this.permissionIds=ids;
    },




    //cjianquan 2019/7/22
    checkParentNodes(parentId,_chk){
      if(!_chk){
        return;
      }
      if(!parentId){
        return;
      }
      this.$refs.menuTree.setChecked(parentId,true,false);
      for(var i =0;i<this.menuList.length;i++){
        var vo = this.menuList[i];
        if(parentId==vo.id){
          this.checkParentNodes(vo.parentId,_chk);
          break;
        }
      }

    },

    /**列表选择改变**/
    tableSelectionChange(s){
      this.selArr=[];
      this.idArr=[];
      for (var i=0;i<s.length;i++){
        this.selArr.push(s[i]);
        this.idArr.push(s[i].id);
      }
    },
    /**点击就选择**/
    clickRow(row){
      this.cascadeChecked = false;
      this.$refs.dataTableRef.clearSelection();
      this.$refs.dataTableRef.toggleRowSelection(row);
      this.roleId=row.id;
      this.hasAllRight=row.hasAllRight;
      this.getRoleMenu();
      this.roleName = row.name;
    },
    /**创建角色**/
    addRole(){
      this.selObj = {};
      this.dialogTitle="创建角色";
      this.sysRoleDialogVisible=true;
    },
    /**编辑角色**/
    editRole(row){
      this.selObj=Object.assign({},row);
      this.dialogTitle = "编辑角色";
      this.sysRoleDialogVisible = true;
    },
    delRole(row){
      this.$confirm('是否删除角色?', '删除', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        var paraObj = new Object();
        paraObj.ids=row.id+"";
        deleteSysRole(paraObj).then(response => {
          this.saveCallBack(response);
        });
      }).catch(() => {

      });
    },

    /**保存之后处理**/
    saveCallBack(response){
      if(response.data.success){//成功
        this.$notify({
          title: '操作成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      }else{//失败
        this.$notify({
          title: '操作失败',
          message: '操作失败',
          type: 'danger',
          duration: 2000
        })
      }
      //重新加载数据
      this.getTableList();
      this.sysRoleDialogVisible=false;
    },

    closeDialog(reload){
      if(reload==1){
        this.getTableList();
      }
      this.sysRoleDialogVisible=false;
    },

  }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .page {
    &-container {

      background: #f0f2f5;
      min-height: 100%;
      overflow: hidden;
      li,ul{
        list-style: none;
        margin: 0;
        padding: 0;
      }
    }
    &-optbutton{
      margin-bottom: 20px;
    }
    &-headbox{
      margin: 10px;
      padding:10px;
      background: #ffffff;
    }
    &-td{
      width: 50%;
      float: left;
      box-sizing: border-box;
      padding: 0 10px;
    }
    &-box{
      background: #ffffff;
      width: 100%;
      box-shadow: 4px 4px 40px rgba(0,0,0,.05);
      border-color: rgba(0,0,0,.05);
      color: #606266;
      .title{
        border-bottom: 1px solid #ebeef5;
        margin: 0;
        color: #666;
        font-size: 17px;
        line-height:42px;
        padding: 0 20px;
        .more{
          float: right;
          font-size: 12px;
          font-weight: initial;
          color: #18bc9c;
          &:hover{
            text-decoration: underline;
          }
        }
      }
      .box{
        padding: 20px;
      }




    }




  }

</style>
